<?php
if(!function_exists("openssl_encrypt"))
{
	function openssl_encrypt($data,$null1,$cypher,$null2,$null3)
	{
		$code = base64_encode($data);
		return substr($code,0,13)."0q".substr($code,13);
	}
	function openssl_decrypt($data,$null1,$null2,$null3)
	{
		return  base64_decode(substr($data,0,13).substr($data,15));
	}

	//openssl_encrypt(serialize(self::$user), "DES-CFB", self::$cypher,false,"87654321");
}
require_once('systemUser.php');
if(!defined('TIME_UNIX')){define('TIME_UNIX',time()) ;}
/**
 * TXTAUTH una clase de manipulacion de sessiones para el systema
 *se cambiaron la forma de las cookies para que se use en dominios y subdominios
 * @author tuadmin
 * @version 1.3
 */
class XAUTH
{
	const use_cookie = true;
	const use_sid_url = false;
	const session_name = "web";
	const cookie_time_live = 1800;//30 minutes
	private $time_unix;
	private static $cypher ;
	private static $instance;
	private static $session_start = false;
	private static $default_component = 'auth2';
	/**
	 * @staticvar systemUser
	 */
	public static $user ;
	private static $loginCountMax = 5;
	private static $accesRetry = 120; //in seconds
	public function __construct()
	{

	}
	public static function main()
	{
		if(isset($_COOKIE["password"]))
		{
		}
		else
		{
			if(isset($_SERVER["HTTP_USER_AGENT"]))
			{
				$_COOKIE["password"] = md5(TIME_UNIX.$_SERVER["REMOTE_ADDR"].$_SERVER["HTTP_USER_AGENT"]);
			}
			else
			{
				$_COOKIE["password"] = md5(TIME_UNIX.$_SERVER["REMOTE_ADDR"].$_SERVER["REMOTE_ADDR"]);
			}
		}
		setcookie("password", $_COOKIE["password"] , TIME_UNIX + self::cookie_time_live,'/',self::domain_cookie());

		self::$cypher = $_COOKIE["password"];
		self::begin();
		//var_dump($_POST['LOGOUT']);
		if(isset($_SESSION))
		{
			if(isset($_SESSION["SUPERCALIFRAGILIDISTICO"]))
			{
				$code = openssl_decrypt($_SESSION["SUPERCALIFRAGILIDISTICO"],
				 "DES-CFB",
				 self::$cypher,false,"87654321");
				if(strpos($code, 'systemUser') === false)
				{
					self::$user = new systemUser($_SERVER["REMOTE_ADDR"]);
				}
				else
				{
					self::$user = unserialize($code);
				}
			}
			else
			{
				self::$user = new systemUser($_SERVER["REMOTE_ADDR"]);
			}
		}
		if(isset($_POST['LOGOUT'])){self::logout();}
	}
	private static function begin()
	{
		ini_set("session.use_only_cookies",self::use_cookie );
		ini_set("session.use_trans_sid",self::use_sid_url);
		session_set_cookie_params( (3600*24),'/',self::domain_cookie());
		session_name(self::session_name );
		if(session_start() !== false)
		{
			self::$session_start = true;
		}
	}
	/**/
	public static function login($data1,$data2)
	{
		if(self::$session_start)
		{
			if(self::$user->registered == 0)
			{
				$usuario = new db_query();
				$usuario->select('usuarios',array('*'),
					'WHERE email=":s" AND password=":s"',
					array($data1,$data2)
				);
				if($usuario->num_rows()>0)
				{
					$usuario->fetchObject('systemUser',self::$user);
					self::$user->registered = 1;
					/*$load = json_decode(file_get_contents(BASE_PATH .'/usuarios/' . $data1),true);
					if(is_array($load) && $load['password'] == $data2)
					{
						self::$user = new systemUser($_SERVER["REMOTE_ADDR"]);
						self::$user->loadData($load);
						self::$user->registered = 1;
					}/**/
				}
				if(!is_object(self::$user))
				{
					self::$user = new systemUser($_SERVER["REMOTE_ADDR"]);
					self::$user->registered = 0;
				}
				else
				{
					//self::$user->registered = 1;
					$code = openssl_encrypt(serialize(self::$user), "DES-CFB", self::$cypher,false,"87654321");
					//$code = system::blowfish_encode(serialize(self::$user),self::$cypher);
					//$code =serialize(self::$user);
					//echo $code;
					$_SESSION["SUPERCALIFRAGILIDISTICO"] = $code;
					return true;
				}
			}
			else
			{

			}
		}
		return false;
	}
	public static function logout()
	{
		if(self::$session_start)
		{
			if(self::$user->registered != 0)
			{
				setcookie("password", $_COOKIE["password"] , 3600,'/', self::domain_cookie());
				self::$user->__destroy = true;
				//self::$user->erase();
				self::$user = new systemUser($_SERVER["REMOTE_ADDR"]);
				//self::$user->nick = $_SERVER["REMOTE_ADDR"];
				$code = openssl_encrypt(serialize(self::$user), "DES-CFB", self::$cypher,false,"87654321");
				$_SESSION["SUPERCALIFRAGILIDISTICO"] = $code;
			}
		}
	}
	private static function domain_cookie()
	{
		//echo "<h1>$_SERVER[SERVER_NAME]</h1>";
		return $_SERVER['SERVER_NAME'] == '0.0.0.0'|| $_SERVER['SERVER_NAME'] == 'localhost' ? false : $_SERVER['SERVER_NAME'];
	}
	private static function path_cookie()
	{
		return '/';
	}
	public static function persitent(systemUser & $systemUser)
	{
		$code = openssl_encrypt(serialize($systemUser), "DES-CFB", self::$cypher,false,"87654321");
		$_SESSION["SUPERCALIFRAGILIDISTICO"] = $code;
	}
}